package com.ruoyi.analyse.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.analyse.domain.AnalyseRequestBody;
import com.ruoyi.analyse.domain.StudentLearningDimension;
import com.ruoyi.analyse.service.IStudentLearningService;
import com.ruoyi.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.analyse.domain.QuestionAnalysis;
import com.ruoyi.analyse.service.IChatMessageService;
import com.ruoyi.analyse.service.IQuestionAnalysisService;
import com.ruoyi.analyse.service.IStudentProfileService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

/**
 * AI问答系统分析仪表盘
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/analyse/dashboard")
public class DashboardController extends BaseController
{
    @Autowired
    private IQuestionAnalysisService questionAnalysisService;

    @Autowired
    private IStudentProfileService studentProfileService;

    @Autowired
    private IStudentLearningService studentLearningService;

    @Autowired
    private IChatMessageService chatMessageService;

    /**
     * 获取仪表盘基本统计数据
     */
    @PostMapping("/statistics")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getStatistics(@RequestBody AnalyseRequestBody requestBody)
    {
        Long classId = requestBody.getClassId();
        try {
            // 获取总提问数
            int totalQuestions = 0;
            // 这里需要实现统计逻辑，可以从ChatMessage表中统计
            Map<String, Object> result = new HashMap<>();

            // 填充统计数据
            // 1. 总提问数 - 从聊天记录中筛选role=user的记录
            List<Map<String, Object>> dailyStats = chatMessageService.getDailyQuestionStatistics(0, classId); // 0表示获取所有历史数据
            for (Map<String, Object> stat : dailyStats) {
                totalQuestions += ((Number) stat.get("count")).intValue();
            }

            // 2. 参与学生数 - 从学生画像表中统计
            List<Map<String, Object>> activeStudents = studentProfileService.getTopActiveStudents(Integer.MAX_VALUE, classId);

            // 3. 学科分类数 - 从问题分析表中统计不同的学科分类
            List<Map<String, Object>> subjects = questionAnalysisService.getSubjectStatistics(classId);

            // 4. 今日提问数 - 从当天的聊天记录中统计
            List<Map<String, Object>> todayStats = chatMessageService.getDailyQuestionStatistics(1, classId);
            int todayQuestions = todayStats.isEmpty() ? 0 : ((Number) todayStats.get(0).get("count")).intValue();

            result.put("totalQuestions", totalQuestions/2);
            result.put("totalStudents", activeStudents.size());
            result.put("totalSubjects", subjects.size());
            result.put("todayQuestions", todayQuestions/2);

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            return AjaxResult.error("获取统计数据失败");
        }
    }

    /**
     * 获取问题类型分布
     */
    @PostMapping("/questionTypes")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getQuestionTypes(@RequestBody AnalyseRequestBody requestBody)
    {
        try {
//            Map<String, Integer> distribution = questionAnalysisService.getComplexityStatistics();
            Long classId = requestBody.getClassId();
            Map<String, Integer> distribution = questionAnalysisService.getQuestionTypeStatistics(classId);
            System.out.println("问题类型分布：" + distribution);
            List<Map<String, Object>> result = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : distribution.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                String name;

                // 将内部的复杂度类型转换为前端友好的显示文本
                switch (entry.getKey()) {
                    case "SIMPLE":
                        name = "概念解释";
                        break;
                    case "MEDIUM":
                        name = "操作指导";
                        break;
                    case "COMPLEX":
                        name = "原理分析";
                        break;
                    case "比较分析":
                        name = "比较分析";
                        break;
                    case "代码实现":
                        name = "代码实现";
                        break;
                    case "错误诊断":
                        name = "错误诊断";
                        break;
                    case "优化建议":
                        name = "优化建议";
                        break;
                    default:
                        name = "一般提问";
                }

                item.put("name", name);
                item.put("value", entry.getValue());
                result.add(item);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取问题类型分布失败", e);
            return AjaxResult.error("获取问题类型分布失败");
        }
    }

    /**
     * 获取学科分布
     */
    @PostMapping("/subjects")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getSubjects(@RequestBody AnalyseRequestBody requestBody)
    {
        try {
            Long classId = requestBody.getClassId();
            // 修改这里，使用getSubjectStatistics方法替代countQuestionsBySubject
            List<Map<String, Object>> subjects = questionAnalysisService.getSubjectStatistics(classId);

            List<Map<String, Object>> result = new ArrayList<>();
            for (Map<String, Object> subject : subjects) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", subject.get("subject"));
                item.put("value", subject.get("count"));
                result.add(item);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取学科分布失败", e);
            return AjaxResult.error("获取学科分布失败");
        }
    }

    /**
     * 获取复杂度分布
     */
    @PostMapping("/complexity")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getComplexityDistribution(@RequestBody AnalyseRequestBody requestBody)
    {
        Long classId = requestBody.getClassId();
        try {
            Map<String, Integer> distribution = questionAnalysisService.getComplexityStatistics(classId);
            return AjaxResult.success(distribution);
        } catch (Exception e) {
            logger.error("获取复杂度分布失败", e);
            return AjaxResult.error("获取复杂度分布失败");
        }
    }

    /**
     * 获取每日提问趋势
     */
    @PostMapping("/dailyTrend")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getDailyTrend(@RequestBody AnalyseRequestBody requestBody)
    {
        Long classId = requestBody.getClassId();
        try {
            // 获取最近30天的数据
            List<Map<String, Object>> dailyStats = chatMessageService.getDailyQuestionStatistics(30,classId);

            List<Map<String, Object>> result = new ArrayList<>();
            SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd");
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");

            for (Map<String, Object> stat : dailyStats) {
                Map<String, Object> item = new HashMap<>();

                // 检查是否有day字段（从数据库查询）
                String day = (String) stat.get("day");
                if (day != null) {
                    // 将字符串格式的日期转换为Date对象，再格式化为所需格式
                    try {
                        Date date = inputFormat.parse(day);
                        item.put("date", outputFormat.format(date));
                    } catch (ParseException e) {
                        item.put("date", "格式错误");
                    }
                }
                // 检查是否有date字段（从默认数据生成）
                else if (stat.get("date") != null) {
                    Date date = (Date) stat.get("date");
                    item.put("date", outputFormat.format(date));
                }
                // 如果两者都没有
                else {
                    item.put("date", "N/A");
                }

                item.put("count", stat.get("count"));
                result.add(item);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取每日提问趋势失败", e);
            return AjaxResult.error("获取每日提问趋势失败");
        }
    }


    /**
     * 获取热门关键词
     */
    @PostMapping("/hotKeywords")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getHotKeywords(@RequestBody AnalyseRequestBody requestBody)
    {
        Long classId = requestBody.getClassId();
        try {
            // 获取前20个热门关键词
            List<QuestionAnalysis> keywords = questionAnalysisService.getTopKeywords(20, classId);

            List<Map<String, Object>> result = new ArrayList<>();
            for (QuestionAnalysis qa : keywords) {
                Map<String, Object> item = new HashMap<>();
                item.put("keyword", qa.getKeyword());
                item.put("frequency", qa.getFrequency());
                result.add(item);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取热门关键词失败", e);
            return AjaxResult.error("获取热门关键词失败");
        }
    }

    /**
     * 获取最活跃学生
     */
    @PostMapping("/activeStudents")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getActiveStudents(@RequestBody AnalyseRequestBody requestBody)
    {
        Long classId = requestBody.getClassId();
        try {
            // 获取前10个最活跃的学生
            List<Map<String, Object>> activeStudents = studentProfileService.getTopActiveStudents(10, classId);
            return AjaxResult.success(activeStudents);
        } catch (Exception e) {
            logger.error("获取最活跃学生失败", e);
            return AjaxResult.error("获取最活跃学生失败");
        }
    }

    /**
     * 获取学生学习画像
     */
    @GetMapping("/studentProfile")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public AjaxResult getStudentProfile(@RequestParam("userName") String userName)
    {
        try {
            Map<String, Object> profile = studentProfileService.getStudentLearningProfile(userName);
            // 将学习维度加入到返回结果中
            if (profile != null) {
                // 获取学习维度评估
                List<StudentLearningDimension> dimensions = studentLearningService.getStudentLearningDimensions(userName);

                // 动态计算学习状态
                String learningStatus = studentLearningService.calculateLearningStatus(dimensions);
                profile.put("learningStatus", learningStatus);

                // 动态生成学习建议
                List<Map<String, String>> recommendations = studentLearningService.generateLearningRecommendations(dimensions);
                profile.put("recommendationItems", recommendations);

                // 添加学习维度数据
                profile.put("learningProgressItems", dimensions);
            }
            return AjaxResult.success(profile);
        } catch (Exception e) {
            logger.error("获取学生学习画像失败", e);
            return AjaxResult.error("获取学生学习画像失败");
        }
    }

}
